
$j = jQuery.noConflict();

var lc = {
	editMode: false,
	fields: [],
	editor: null
}

$j(function() {
	
	$j(document).keydown(function (evt) {
		
		if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == 69) {
			if (lc.editMode) {
				lc.editMode = false;
				$j('.lc_toolbar').remove();
				var margin = parseInt($j('body').css('margin-top'));
				$j('body').css('margin-top', (margin - 26) + 'px' );
				$j.each(lc.fields, function(i, field) {
					$j(field.path).attr('contenteditable', null).blur();
				});
				
				$j.put('', $j('body').html());
			} else {
				lc.editMode = true;
				initialize();
			}
		}
	});
	
});

function initialize() {
	
	$j.getJSON('?fields', function (fields) {
		lc.fields = fields;
		$j.each(fields, function(i, field) {
			$j(field.path).attr('contenteditable', 'true').each(function(i, elem) {
				elem.editor = WysiHat.Editor.attach(elem, {model: WysiHat.Inline});
			});
		});
	});
	
	var margin = parseInt($j('body').css('margin-top'));
	$j('body').prepend('<div class="lc_toolbar" style="position:fixed;height:24px;top:0px;left: 0px;right: 0px;padding: 2px;background: #3b3b35;text-align:left">\
		<button style="width:26px;height:24px;" class="bold">B</button>\
		<button style="width:26px;height:24px;" class="italic">I</button>\
	</div>').css('margin-top', (margin + 26) + 'px' );
	
	$j('.lc_toolbar button').click(function() {
		document.execCommand(this.className, false, null);
	});
}

